package com.cayden.componets.canal.handle;


import com.alibaba.otter.canal.protocol.FlatMessage;
import com.cayden.config.boot.Apps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * @author cayden
 * @version V1.0
 * @date 2020/12/5 10:23
 */
@Component
@Slf4j
public class CanalFirstHandleContextInfo {

    private static final char SEPARATOR = '_';


    public void doChangeHandleInfo(CanalContext canalContext) {
        FlatMessage flatMessage = canalContext.getFlatMessage();
        //初步判断数据
        if (flatMessage == null || CollectionUtils.isEmpty(flatMessage.getData())) {
            return;
        }

        String childClassInfo = changeChildClassInfo(flatMessage);
        CanalHandle canalHandle = null;
        try {
            canalHandle = Apps.getApplicationContext().getBean(childClassInfo, CanalHandle.class);
        } catch (NoSuchBeanDefinitionException beanDefineError) {
            log.info("CanalClient:[{} Handler未定义跳过处理]", childClassInfo);
        } catch (Exception e) {
            log.error("处理canal同步失败", e);
            return;
        }
        if (canalHandle == null) {
            return;
        }
        canalHandle.printCanalLog(flatMessage);
        canalHandle.handleInfo(canalContext);
    }

    /**
     * 子类规则应该是 数据库 + table + CanalHandle
     */
    protected String changeChildClassInfo(FlatMessage flatMessage) {
        String result = "";
        String database = flatMessage.getDatabase();
        String table = flatMessage.getTable();
        result = toCamelCase(database) + castFirstCapital(toCamelCase(table)) + "CanalHandle";
        return result;
    }

    protected String castFirstCapital(String inner) {
        return inner.substring(0, 1).toUpperCase() + inner.substring(1);
    }

    protected String toCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = s.toLowerCase();
        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == SEPARATOR) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }


}
